<template>
  <div class="system-logs">
    <div class="page-header">
      <h2>系统日志</h2>
      <div class="header-actions">
        <el-select
          v-model="logType"
          placeholder="日志类型"
          clearable
          style="width: 150px; margin-right: 16px"
          @change="loadLogs"
        >
          <el-option label="全部" value="" />
          <el-option label="登录日志" value="login" />
          <el-option label="操作日志" value="operation" />
          <el-option label="错误日志" value="error" />
        </el-select>
        <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期"
          style="margin-right: 16px"
          @change="loadLogs"
        />
        <el-button :icon="Refresh" @click="loadLogs">刷新</el-button>
        <el-button type="danger" :icon="Delete" @click="handleClear">清空日志</el-button>
      </div>
    </div>

    <!-- 日志表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="id" label="日志ID" width="100" />
      <el-table-column prop="type" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getLogTypeTag(row.type)">
            {{ getLogTypeName(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户" width="150" />
      <el-table-column prop="action" label="操作" width="200" />
      <el-table-column prop="ip" label="IP地址" width="150" />
      <el-table-column prop="content" label="日志内容" min-width="300" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Delete } from '@element-plus/icons-vue'
import { getSystemLogList, clearAllLogs } from '../api/systemLog'

// 数据
const tableData = ref([])
const loading = ref(false)
const logType = ref('')
const selectedDate = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

onMounted(() => {
  loadLogs()
})

// 加载日志
const loadLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    if (logType.value) {
      params.type = logType.value
    }
    
    if (selectedDate.value) {
      params.date = formatDateForApi(selectedDate.value)
    }
    
    const response = await getSystemLogList(params)
    if (response.code === 200) {
      tableData.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载日志失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载日志失败：', error)
    ElMessage.error('加载日志失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 清空日志
const handleClear = () => {
  ElMessageBox.confirm(
    '确定要清空所有日志吗？此操作不可恢复！',
    '清空确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await clearAllLogs()
      if (response.code === 200) {
        ElMessage.success('清空成功')
        loadLogs()
      } else {
        ElMessage.error(response.message || '清空失败')
      }
    } catch (error) {
      console.error('清空日志失败：', error)
      ElMessage.error('清空日志失败')
    }
  })
}

// 获取日志类型标签
const getLogTypeTag = (type) => {
  const tags = {
    login: 'success',
    operation: 'info',
    error: 'danger'
  }
  return tags[type] || 'info'
}

// 获取日志类型名称
const getLogTypeName = (type) => {
  const names = {
    login: '登录日志',
    operation: '操作日志',
    error: '错误日志'
  }
  return names[type] || type
}

// 分页
const handleSizeChange = (size) => {
  pageSize.value = size
  loadLogs()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadLogs()
}

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 格式化日期为API参数（YYYY-MM-DD）
const formatDateForApi = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
</script>

<style scoped>
.system-logs {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  font-size: 20px;
  color: #303133;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}
</style>

